/*
 * RSAappView.java
 */

package rsaapp;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import rsa.lib.Key;
import rsa.min.DecryptFile;
import rsa.min.EncryptFile;

/**
 * The application's main frame.
 */
public class RSAappView extends FrameView {

    public RSAappView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                //statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        //statusAnimationLabel.setIcon(idleIcon);
        //progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        //statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    //progressBar.setVisible(true);
                    //progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    //statusAnimationLabel.setIcon(idleIcon);
                    //progressBar.setVisible(false);
                    //progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    //statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    //progressBar.setVisible(true);
                    //progressBar.setIndeterminate(false);
                    //progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = RSAappApp.getApplication().getMainFrame();
            aboutBox = new RSAappAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        RSAappApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        txtInputFile = new javax.swing.JTextField();
        txtOutputFile = new javax.swing.JTextField();
        btnInput = new javax.swing.JButton();
        btnKey = new javax.swing.JButton();
        txtKeyFile = new javax.swing.JTextField();
        btnOutput = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        txtInfo = new javax.swing.JLabel();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(rsaapp.RSAappApp.class).getContext().getResourceMap(RSAappView.class);
        txtInputFile.setFont(resourceMap.getFont("txtInputFile.font")); // NOI18N
        txtInputFile.setText(resourceMap.getString("txtInputFile.text")); // NOI18N
        txtInputFile.setName("txtInputFile"); // NOI18N

        txtOutputFile.setFont(resourceMap.getFont("txtOutputFile.font")); // NOI18N
        txtOutputFile.setText(resourceMap.getString("txtOutputFile.text")); // NOI18N
        txtOutputFile.setName("txtOutputFile"); // NOI18N

        btnInput.setText(resourceMap.getString("btnInput.text")); // NOI18N
        btnInput.setName("btnInput"); // NOI18N
        btnInput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInputActionPerformed(evt);
            }
        });

        btnKey.setText(resourceMap.getString("btnKey.text")); // NOI18N
        btnKey.setName("btnKey"); // NOI18N
        btnKey.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnKeyActionPerformed(evt);
            }
        });

        txtKeyFile.setFont(resourceMap.getFont("txtKeyFile.font")); // NOI18N
        txtKeyFile.setText(resourceMap.getString("txtKeyFile.text")); // NOI18N
        txtKeyFile.setName("txtKeyFile"); // NOI18N

        btnOutput.setText(resourceMap.getString("btnOutput.text")); // NOI18N
        btnOutput.setName("btnOutput"); // NOI18N
        btnOutput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOutputActionPerformed(evt);
            }
        });

        jButton4.setText(resourceMap.getString("jButton4.text")); // NOI18N
        jButton4.setName("jButton4"); // NOI18N
        jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton4MouseClicked(evt);
            }
        });

        jButton5.setText(resourceMap.getString("jButton5.text")); // NOI18N
        jButton5.setName("jButton5"); // NOI18N
        jButton5.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton5MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jButton4)
                        .addGap(18, 18, 18)
                        .addComponent(jButton5))
                    .addComponent(txtInputFile, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtOutputFile, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtKeyFile, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnInput, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnOutput, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnKey, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(14, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btnInput, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtInputFile, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtOutputFile, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnOutput, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(23, 23, 23)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnKey, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtKeyFile, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(179, 179, 179)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        fileMenu.add(jMenuItem1);

        jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem2);

        jSeparator1.setName("jSeparator1"); // NOI18N
        fileMenu.add(jSeparator1);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(rsaapp.RSAappApp.class).getContext().getActionMap(RSAappView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        txtInfo.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        txtInfo.setText(resourceMap.getString("txtInfo.text")); // NOI18N
        txtInfo.setName("txtInfo"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup()
                .addContainerGap(286, Short.MAX_VALUE)
                .addComponent(txtInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtInfo, javax.swing.GroupLayout.DEFAULT_SIZE, 16, Short.MAX_VALUE)
                .addContainerGap())
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

private void btnInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInputActionPerformed
// TODO add your handling code here:
    txtInputFile.setText(null);
    txtOutputFile.setText(null);
    txtKeyFile.setText(null);
    txtInfo.setText(null);
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    int returnVal = fc.showOpenDialog(null);
    
    if(returnVal == JFileChooser.APPROVE_OPTION){
        File file = fc.getSelectedFile();
        this.infile = file;
        txtInputFile.setText(file.getAbsolutePath());
    }else{
        this.infile = null;
    }
    //progressBar.setIndeterminate(true);
}//GEN-LAST:event_btnInputActionPerformed

private void btnOutputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOutputActionPerformed
// TODO add your handling code here:
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int returnVal = fc.showOpenDialog(null);

    if(returnVal == JFileChooser.APPROVE_OPTION){
        File file = fc.getSelectedFile();
        this.outfile = file;
        txtOutputFile.setText(file.getAbsolutePath());
    }else{
        this.outfile = null;
    }
    //progressBar.setIndeterminate(false);
}//GEN-LAST:event_btnOutputActionPerformed

private void btnKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnKeyActionPerformed
// TODO add your handling code here:
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    int returnVal = fc.showOpenDialog(null);
    
    if(returnVal == JFileChooser.APPROVE_OPTION){
        File file = fc.getSelectedFile();
        this.keyfile = file;
        txtKeyFile.setText(file.getAbsolutePath());
    }else{
        this.keyfile = null;
    }
}//GEN-LAST:event_btnKeyActionPerformed

private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
// TODO add your handling code here:
    JFrame mainFrame = RSAappApp.getApplication().getMainFrame();
    if(createKey == null){
        createKey = new Createkey();
        createKey.setLocationRelativeTo(mainFrame);
        createKey.setDad(mainFrame);
    }
    RSAappApp.getApplication().show(createKey);
    createKey.setVisible(true);
    mainFrame.setVisible(false);
}//GEN-LAST:event_jMenuItem2ActionPerformed

private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseClicked
// TODO add your handling code here:
    //String pkfile = txtKeyFile.getText();
    //String infile = txtInputFile.getText();
    //String outfile = txtOutputFile.getText();
    
    if(keyfile == null)
        keyfile = new File("public.key");
    if(infile == null)
        infile = new File("input.txt");
    if(outfile == null){
        String path = infile.getParent();
        path = path + "\\" + infile.getName() + ".encrypted";
        outfile = new File(path);
    }else{
        String path = outfile.getPath();
        path = path + "\\" + infile.getName() + ".encrypted";
        outfile = new File(path);
    }
    
    txtInputFile.setText(infile.getAbsolutePath());
    txtOutputFile.setText(outfile.getAbsolutePath());
    txtKeyFile.setText(keyfile.getAbsolutePath());
    Key pk = null;
    try {
        pk = new Key(keyfile.getAbsolutePath());
    } catch (FileNotFoundException ex) {
        //Logger.getLogger(RSAappView.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, "Can not find key file", "Error",JOptionPane.ERROR_MESSAGE);
    } catch (IOException ex) {
        //Logger.getLogger(RSAappView.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, "Error while reading keyfile", "Error",JOptionPane.ERROR_MESSAGE);
    } catch (ClassNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Invalid key file", "Error",JOptionPane.ERROR_MESSAGE);
    }
    if(pk != null){
        EncryptFile e = new EncryptFile(pk);
        try {
            //progressBar.setIndeterminate(true);
            e.Encrypt(infile.getAbsolutePath(), outfile.getAbsolutePath());
            //progressBar.setIndeterminate(false);
        } catch (IOException ex) {
            //Logger.getLogger(RSAappView.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Error Reading Input File", "Error",JOptionPane.ERROR_MESSAGE);
            //progressBar.setIndeterminate(false);
        }finally{
            txtInfo.setText("Finished");
        }
    }
}//GEN-LAST:event_jButton4MouseClicked

private void jButton5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton5MouseClicked
// TODO add your handling code here:
    if(keyfile == null)
        keyfile = new File("private.key");
    if(infile == null)
        infile = new File("input.txt");
    if(outfile == null){
        String path = infile.getParent();
        path = path + "\\" + infile.getName() + ".dencrypted";
        outfile = new File(path);
    }else{
        String path = outfile.getPath();
        path = path + "\\" + infile.getName() + ".dencrypted";
        outfile = new File(path);
    }
    
    txtInputFile.setText(infile.getAbsolutePath());
    txtOutputFile.setText(outfile.getAbsolutePath());
    txtKeyFile.setText(keyfile.getAbsolutePath());
    Key pk = null;
    try {
        pk = new Key(keyfile.getAbsolutePath());
    } catch (FileNotFoundException ex) {
        //Logger.getLogger(RSAappView.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, "Can not find key file", "Error",JOptionPane.ERROR_MESSAGE);
    } catch (IOException ex) {
        //Logger.getLogger(RSAappView.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, "Error while reading key file", "Error",JOptionPane.ERROR_MESSAGE);
    } catch (ClassNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Invalid key file", "Error",JOptionPane.ERROR_MESSAGE);
    }
    if(pk != null){
        DecryptFile e = new DecryptFile(pk);
        try {
            //progressBar.setIndeterminate(true);
            e.Decrypt(infile.getAbsolutePath(), outfile.getAbsolutePath());
            //progressBar.setIndeterminate(false);
        } catch (IOException ex) {
            //Logger.getLogger(RSAappView.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Error Reading Input File", "Error",JOptionPane.ERROR_MESSAGE);
            //progressBar.setIndeterminate(false);
        }finally{
            txtInfo.setText("Finished");
        }
    }
}//GEN-LAST:event_jButton5MouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnInput;
    private javax.swing.JButton btnKey;
    private javax.swing.JButton btnOutput;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JLabel txtInfo;
    private javax.swing.JTextField txtInputFile;
    private javax.swing.JTextField txtKeyFile;
    private javax.swing.JTextField txtOutputFile;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
    private final JFileChooser fc = new JFileChooser();
    private Createkey createKey;
    private File infile;
    private File outfile;
    private File keyfile;
}
